<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
	<th:block th:include="include :: header('供应商资料新增及修改')" />
	<style type="text/css">
		.layui-form-label {width: 110px;height: 36px;line-height: 36px;padding: 0;}
		.layui-elem-quote b{text-indent:50px;color:#142A48;font-size:20px;}
		.layui-col-md4{width:32%}
		.layui-form-item{margin-bottom:16px}
		.getUpload{color: #009688;font-size: 18px;position: absolute;top:5px;right: 9px;}
		.layui-disabled{color: #999 !important}
		.mid-content{padding:0 !important;}
		.layui-form-item {clear: both;margin-top: 0;background: #FFFFFF;}
		.layui-form-item .layui-inline {margin: 10px 5px}
	</style>
</head>
<body>
<form class="layui-form" id="form-provider-add" style="padding: 0 0 0 0;">
<input type="hidden" id="guid" name="guid"  th:value="${guid}">
<input type="hidden" name="bShared"  th:value="${providerInfo?.bShared?:0}">
<div id="top_height" style="margin-top: 16px">
	<blockquote class="layui-elem-quote"><b>供应商基础资料</b></blockquote>
	<div class="layui-form-item">
		<div th:each="field:${gridColumns.dictionaryForPageFieldList}" th:if="${field.fieldFrontTop} eq '1' and !${field.fieldFrontHidden}" th:remove="tag">
			<div th:if="${field.fields} eq 'gprovide' and ${providerInfo}" class="layui-inline layui-col-md4">
			  <label class="layui-form-label">供应商编号：</label>
			  <div class="layui-input-block">
			    <input type="text" name="gprovide" id="gprovide"  autocomplete="off" placeholder="请输入" class="layui-input layui-disabled" readonly>
			  </div>
			</div>
			<div th:if="${field.fields} ne 'gprovide'" class="layui-inline layui-col-md4">
				<label class="layui-form-label" th:utext="(${field.fieldFrontRequired}?'<font class=\'f_red\'>*</font>':'') +${field.fieldName}+'：'"></label>		
				<div class="layui-input-block">
				  	<input th:if="${field.fieldFrontType} eq 't_text'" type="text" autocomplete="off" placeholder="请输入" 
				  		th:id="${field.fields}" th:name="${field.fields}" th:readonly="${field.fields eq 'mainBrand'}?'true':'false'" th:style="${field.fields eq 'mainBrand'}?'padding-right:25px':''"
				  		class="layui-input" th:lay-verify="${field.fieldFrontRequired}?'required':''">
				  		<i th:if="${field.fields} eq 'mainBrand'" class="layui-icon layui-icon-more" style="position:absolute;top:5px;right:5px" onclick="chooseMainBrand()"></i>
				  	<select th:if="${field.fieldFrontType} eq 't_dropdown'" th:id="${field.fields}" th:name="${field.fields}" th:with="vtype=${#strings.substringAfter(#strings.substringAfter(field.fieldSearchType,'_'),'_')}" th:lay-verify="${field.fieldFrontRequired}?'required':''">
				  		<div th:with="type=${@baseinfosimple.getBaseInfoSimpleData(vtype)}" th:remove="tag">
							<option value="">请选择</option>
							<option th:each="dict : ${type}" th:text="${dict.vname}" th:value="${dict.vid}"></option>
				  		</div>
					</select>
					<input th:if="${field.fieldFrontType} eq 't_date' or ${field.fieldFrontType} eq 't_datetime' or ${field.fieldFrontType} eq 't_year'" type="text" th:name="${field?.fields}" th:id="${field?.fields}" autocomplete="off" class="layui-input t_date" th:lay-verify="${field.fieldFrontRequired}?'required':''" readonly>
                    	<i th:if="(${field.fieldFrontType} eq 't_date' or ${field.fieldFrontType} eq 't_datetime' or ${field.fieldFrontType} eq 't_year')" class="dhicon dh-calendar icon_date_business"></i>
				</div>
			</div>
		</div>
		<div class="layui-inline layui-col-md4 dispalyselect">
		  <label class="layui-form-label">省市区：</label>
		  	<div class="layui-input-block">
		  		<div style="width:49%;display:inline-block">
			  	 	<select id="province" name="province" lay-filter="province" th:with="type=${@baseinfosimple.getBaseInfoSimpleData('area2')}">
						<option></option>
						<option th:each="dict : ${type}" th:text="${dict.vname}" th:data-guid="${dict.guid}" th:value="${dict.vid}" th:selected="${dict.vid} eq ${providerInfo?.province}"></option>
					</select>
				</div>
				<div style="width:49%;display:inline-block">
					<select id="city" name="city" lay-filter="city">
					</select>
				</div>
			</div>
	<!-- 		<div class="layui-input-inline" id="areaDiv"> -->
	<!-- 			<select id="area" name="area" lay-filter="area" th:with="type=${@baseinfosimple.getBaseInfoSimpleData('area4')}"> -->
	<!-- 				<option value="">请选择</option> -->
	<!-- 				<option th:each="dict : ${type}" th:text="${dict.vname}" th:data-guid="${dict.guid}" th:value="${dict.vid}" th:selected="${dict.vid} eq ${providerInfo?.area}"></option> -->
	<!-- 			</select> -->
	<!-- 	  	</div> -->
		</div>
		<div th:if="${providerInfo}" class="layui-inline layui-col-md4">
		  <label class="layui-form-label">附件：</label>
		  <div class="layui-input-block">
		    <input type="text" id="vProviderFiles" th:value="${providerInfo?.vProviderFiles}" autocomplete="off" class="layui-input" readonly>
		    <i class="layui-icon layui-icon-upload getUpload" onclick="uploadFile();" gettype="vProviderFiles"></i>
		  </div>
		</div>
	</div>
	<blockquote class="layui-elem-quote"><b>供应商财务资料</b></blockquote>
	<div class="layui-form-item">
		<div th:each="field:${gridColumns.dictionaryForPageFieldList}" th:if="${field.fieldFrontTop} eq '5' and !${field.fieldFrontHidden}" class="layui-inline layui-col-md4">
			<label class="layui-form-label" th:utext="(${field.fieldFrontRequired}?'<font class=\'f_red\'>*</font>':'') +${field.fieldName}+'：'"></label>		
			<div class="layui-input-block">
			  	<input th:if="${field.fieldFrontType} eq 't_text'" type="text" autocomplete="off" placeholder="请输入" th:id="${field.fields}" th:name="${field.fields}" class="layui-input" th:lay-verify="${field.fieldFrontRequired}?'required':''">
			  	<select th:if="${field.fieldFrontType} eq 't_dropdown'" th:id="${field.fields}" th:name="${field.fields}" th:with="vtype=${#strings.substringAfter(#strings.substringAfter(field.fieldSearchType,'_'),'_')}" th:lay-verify="${field.fieldFrontRequired}?'required':''">
			  		<div th:with="type=${@baseinfosimple.getBaseInfoSimpleData(vtype)}" th:remove="tag">
						<option value="">请选择</option>
						<option th:each="dict : ${type}" th:text="${dict.vname}" th:value="${dict.vid}" th:selected="${dict.vid} eq ${providerInfo?.trade}"></option>
			  		</div>
				</select>
			</div>
		</div>
	</div>
</div>
<blockquote class="layui-elem-quote"><b>供应商联系人</b>
<div th:if="!${canntEdit}" class="layui-btn layui-btn-normal layui-table-tools" onClick="addRow()" style="float:right">
	<p class="dhicon dh-plus" style="color:white;font-size:14px;margin-left: -35px;"><span class="fa_span">新增</span></p>
</div>
</blockquote>
<div class="layui-form-item layui-hide">
  <input type="button" lay-submit="" lay-filter="btn_save" id="btn_save" value="保存">
</div>
<div class="mid-content">
    <table class="layui-hide" id="dhtable" lay-filter="ftable"></table>
</div>
<div class="layui-col-md12">
	<div class="layui-btn-container" style="float: right;margin: 10px;">
		<input th:if="!${canntEdit}" class="layui-btn layui-table-tools" type="button" lay-submit="" lay-filter="btn_save" value="保存">
        <input th:if="${providerInfo==null}" class="layui-btn layui-btn-normal layui-table-tools" type="button" lay-submit="" lay-filter="btn_savenew" value="保存并新建" id="saveNew">
		<input class="layui-btn layui-btn-primary layui-table-tools" type="button" onclick="closeTab()" value="关闭" style="color:#fff;">
    </div>
</div>
</form>
<script type="text/html" id="barDh">
    <a th:class="${canntEdit}?'layui-btn layui-btn-xs dhicon dh-remove layui-btn-disabled':'layui-btn layui-btn-danger layui-btn-xs dhicon dh-remove'" th:lay-event="${canntEdit}?'':'del'">&nbsp;删除</a>
</script>
<script type="text/html" id="bfkH">
    <input type="radio" name="bfk" {{ d.bfk == 1 ? 'checked' : '' }} th:disabled="${canntEdit}">      
</script>
<script type="text/html" id="blxrH">
    <input type="radio" name="blxr" {{ d.blxr == 1 ? 'checked' : '' }} th:disabled="${canntEdit}">      
</script>
<script type="text/html" id="bshH">
    <input type="radio" name="bsh" {{ d.bsh == 1 ? 'checked' : '' }} th:disabled="${canntEdit}">        
</script>
<script type="text/html" id="bspH">
    <input type="radio" name="bsp" {{ d.bsp == 1 ? 'checked' : '' }} th:disabled="${canntEdit}">
</script>
<!-- 主营品牌 -->
<script id="chooseMainBrand" type="text/template">
	<table class="layui-hide" id="dhtable_c" lay-filter="ftable_c"></table>
</script>
<script type="text/html" id="cmb_tb">
	<a class="layui-btn layui-btn-normal layui-table-tools dhicon dh-plus" lay-event="addBtn">&nbsp;新增</a>
	<a class="layui-btn layui-btn-danger layui-table-tools dhicon dh-remove" lay-event="delBtn">&nbsp;删除</a>
</script>
<script type="text/html" id="tpl_mb">
	<input type="text" value="{{d.mainBrand?d.mainBrand:''}}" class="layui-input" style="position:absolute;overflow:hidden;z-index:2;width: calc(100% - 33px);" onChange="inputSearchTable(this,'mainBrand')" autocomplete="off">
	<select th:with="map=${@baseinfosimple.getDropdownData('TB_baseinfo_brand','vname','vname')}" lay-filter="select_table" class="layui-select" lay-search>
		<option></option>
		<div th:each="dict : ${map}" th:utext="'<option value=\''+${dict.vid}+'\' {{d.mainBrand==\''+${dict.vid}+'\'?\'selected\':\'\'}}>'+${dict.vname}+'</option>'" th:remove="tag"><div>
	</select>
</script>
<th:block th:include="include :: footer" />
<th:block th:include="include :: motif-alone" />
<script th:src="@{/dhecp/js/selectInTable.js?v=1}"></script>
<script th:inline="javascript">
	/*<![CDATA[*/
	var prefix1 = ctx + "crm/provider";
	var prefix2 = ctx + "crm/providerpersion", cCityName = [[${providerInfo?.city}]];
	var canntEdit=[[${canntEdit}]],//是否不可编辑（仅适用于他人查看详情）
		gridColumns=[[${gridColumns}]],
		providerInfo=[[${providerInfo}]],
		moduleTable=[[${moduleTable}]];
	/*]]>*/
</script>
<script type="text/javascript">
var $,layer,form,table,laydate,listData,gprovide;
layui.use(['table','form','layer','jquery','laydate'], function () {
    $ = layui.$,layer = layui.layer,form = layui.form,table = layui.table,laydate= layui.laydate;
    var tableBody=[[
   	 	{type:'numbers',rowspan: 2},
        {field: 'vName',title: "<font class='f_red'>*</font>姓名",rowspan: 2,edit:'text'},
       	{field: 'vTel',title: "<font class='f_red'>*</font>电话",rowspan: 2,edit:'text'},
       	{field: 'vWxh',title: '微信号',rowspan: 2,edit:'text'},
       	{field: 'vQQ',title: 'QQ',rowspan: 2,edit:'text'},
       	{field: 'vAddress',title: "<font class='f_red'>*</font>地址",rowspan: 2,edit:'text'},
        {field: 'vFax',title: '传真',rowspan: 2,edit:'text'},
        {field: 'vMail',title: '邮箱',rowspan: 2,edit:'text'},
        {align: 'center',title: '默认设置',colspan:4},
        {title: '操作',align: 'center',templet:'#barDh',rowspan: 2}
    ], [
        {field: 'bfk', title: '收款人',width:75,event: 'check',templet:'#bfkH'},
        {field: 'blxr', title: '联系人',width:75,event: 'check',templet:'#blxrH'},
        {field: 'bsh', title: '发货人',width:75,event: 'check',templet:'#bshH'},
        {field: 'bsp', title: '开票人',width:75,event: 'check',templet:'#bspH'}
    ]
	]
    if(providerInfo){//存在providerInfo对象，即编辑页面，赋值
    	$.each(providerInfo,function(i,v){
    		$('#'+i).val(v);
    	})
    	if(canntEdit){
    		$.each(tableBody[0],function(i,v){delete v['edit']})//移除表格编辑属性
    		$('input').attr('readonly','readonly');
    		$('#top_height input').addClass('layui-disabled');
    		$('select').attr('disabled','disabled');
    	}else laydate.render({elem: '#dZcSj',type:'date',trigger:'click'});
    	form.render('select');
    }else laydate.render({elem: '#dZcSj',type:'date',trigger:'click'});
	$('#gprovide').val()==''? gprovide=null:gprovide=$('#gprovide').val();//通过gprovide判断新增还是修改，来改变下面加载的表格
  	$.ajax({
		url: prefix2 + '/list?gprovide='+gprovide,
        type: "get",
        dataType: "json",
        success: function(result) {
        	listData=result.data;
			$.tablelist.init({
				elem: '#dhtable'
				,modalName: "供应商联系人"
				,data: listData
				,page:false
				,limit:100
				,createUrl: prefix2 + "/add?{id}"
				,updateUrl: prefix2 + "/edit?gprovide={id}"
				,cols: tableBody
				,defaultToolbar:[]
				,height:'full-'+($('#top_height').height()+100)
			});
        }
  	});
	//监听工具条
	table.on('tool(ftable)', function (obj) {
		var data = obj.data, event = obj.event, tr = obj.tr,iName; //获得当前行 tr 的DOM对象;
		iName=this.getAttribute("data-field");
		switch(event){
			case "check":
				$.each(table.cache.dhtable,function(i,v){
					if(v.LAY_TABLE_INDEX==($("tr").index(obj.tr)-2)){//缓存表内的下标和当前事件行下标的判断
						if(tr.find("input[name='"+iName+"']").prop('checked')){
							v[iName]=1;
						}
					}else{
						v[iName]=0;
					}
	        	});
				break;
			case "del":
				if(data.bfk||data.blxr||data.bsh||data.bsp){
					layer.msg("不能删除有默认设置的联系人，请重新操作！",{icon:2});
				}else{
					layer.confirm(data.guid?"该联系人删除将无法恢复，是否确定删除？":"是否删除这条新增联系人？",
						{icon: 3,offset: '10%',title: "系统提示",btn: ['确认', '取消'],yes: function(index){
							if(data.guid)$.operate.post(prefix2 + "/delete/", {'providerPersionInfoItems':JSON.stringify([{'guid':data.guid}])});
							layer.close(index);
							obj.del();//删除对应行（tr）的DOM结构，并更新缓存（变为空数组）
							var listData=table.cache.dhtable;
							for(var i=0; i < listData.length; i++)if(!listData[i] || listData[i].length==0)listData.splice(i, 1);//删除一项
							table.reload('dhtable',{data : listData});
						},btn2: function(){
	        				layer.closeAll();
	        			}
					});
				}
				break;
		}
	});
	//通过gprovide来判断新增、修改\显示隐藏
	if(!$("#gprovide").val()){
		$("#gcDiv").hide();
	}
  	//联动获取城市列表
	form.on('select(province)', function(data){
		$("#city").empty();
		$("#area").empty();
		getCityAndArea(data.elem[data.elem.selectedIndex].dataset.guid,'');
	}); 
	form.on('select(city)', function(data){
		$("#area").empty();
		getCityAndArea('',data.elem[data.elem.selectedIndex].dataset.guid);
	}); 
	function getCityAndArea(value1,value2){
		if(value1){
			$.ajax({
				url: '/base/baseinfo/list?pguid='+value1,
		        type: 'get',
		        dataType: 'json',
				success: function(result) {
					$('#city').append(new Option('请选择城市',''));
					$.each(result.data,function(i,v){
						$('#city').append('<option value="'+v.vname+'" data-guid="'+v.guid+'">'+v.vname+'</option>')
		        	});
					form.render();
				}
			});
		}
		if(value2){
			$.ajax({
				url: '/base/baseinfo/list?pguid='+value2,
		        type: 'get',
		        dataType: 'json',
				success: function(result) {
					$('#area').append(new Option('请选择区县',''));
					$.each(result.data,function(k,v){
						$('#area').append('<option value="'+v.vname+'">'+v.vname+'</option>')
		        	});
					form.render();
				}
			});
		}
	};
	$(function(){
		var cProvince = $("[name=province]").find("option:selected").attr("data-guid");
		if(cProvince){
			$.ajax({
				url: '/base/baseinfo/list?pguid='+cProvince,
		        type: 'get',
		        dataType: 'json',
				success: function(result) {
					$('#city').append(new Option('请选择城市',''));
					$.each(result.data,function(i,v){
						if(v.vname == cCityName){
							$('#city').append('<option value="'+v.vid+'" data-guid="'+v.guid+'" selected>'+v.vname+'</option>')
						}else{
							$('#city').append('<option value="'+v.vid+'" data-guid="'+v.guid+'">'+v.vname+'</option>')
						}
		        	});
					form.render();
				}
			});
		}
	})
	form.on('submit(btn_save)', function(data){
		submitHandler();
	}); 
	form.on('submit(btn_savenew)', function(data){
		submitHandler(true);
	}); 
});
function addRow(){//添加一行联系人
	var listData = table.cache.dhtable;
	if(listData.length==0)listData.push({"bfk":1,"blxr":1,"bsh":1,"bsp":1,"newData":1});
	else listData.push({"bfk":0,"blxr":0,"bsh":0,"bsp":0,"newData":1});
	table.reload('dhtable',{data : listData});
}
function closeTab(){
	top.layui.admin.closeThisTabs();
}
//选择主营品牌
function chooseMainBrand(){
	if(gprovide)layer.open({
		type: 1,
		area: ['400px', '400px'],
		fix: false,//不固定
		offset: '10%',//距离顶部
		maxmin: true,//最大最小化
		shade: 0.3,//遮罩
		title: '主营品牌',
		content: $('#chooseMainBrand').html(),
		btn: ['保存', '取消'],
		shadeClose: true,// 弹层外区域关闭
		success: function(layero, index){
			var layCols=[
				{type: "numbers",fixed: "left"},
				{type: "checkbox",fixed: "left"},
				{field: "mainBrand",title: "主营品牌",align: "center",event:'select_mainBrand',templet:'#tpl_mb'}
			];
		 	$.get("/crm/providermainbrand/list?gprovide="+gprovide,function(res){
				$.tablelist.init({
					elem: '#dhtable_c'
					,data: res.data
   					,toolbar: '#cmb_tb'
					,page: false
					,even: true
					,limit: 1000
					,totalRow: true
			   		,cols: [layCols
					]
					,height:'300'
				});
				table.on('toolbar(ftable_c)', function(obj){
					var checkStatus = table.checkStatus('dhtable_c');
				    switch(obj.event){
				    	case 'addBtn'://新增明细
				    		table.cache.dhtable_c.push({'gprovide':gprovide});//添加空行
				        	table.reload('dhtable_c',{data: table.cache.dhtable_c});
				      		form.render('select');
				    	break;
				    	case 'delBtn'://删除明细
				    		if(checkStatus.data.length == 0){
				    			layer.msg("请先选择！");
				    		}else{
			    				for(var i=table.cache.dhtable_c.length-1; i>=0; i--){//倒序
			    					if(table.cache.dhtable_c[i]["LAY_CHECKED"]){
			    						table.cache.dhtable_c.splice(i, 1);//删除一项
			    					}
			    				}
			    				table.reload('dhtable_c',{data: table.cache.dhtable_c});
				    		}
				    	break;
				    }
				});
				table.on('tool(ftable_c)', function(obj){
					window.inputSearchTable=function (io,field){
						table.cache.dhtable_c[$(io).parents('tr').index()][field]=io.value;
						obj.update(table.cache.dhtable_c[$(io).parents('tr').index()]);//同步行数据，并重新渲染行
						form.render('select');//防止行控件消失——下拉框
					}
					form.on('select(select_table)', function (so) {//监听下拉框
						var value = so.value;	//选中的值
						$(so.elem.parentElement).find('input').val(value);
						$.each(table.cache.dhtable_c,function(i,v){
							if(v.LAY_TABLE_INDEX == obj.tr[0].rowIndex){//缓存表内的下标和当前事件行下标的判断
								v[obj.event.split('_')[1]+'']=value;
							}
						});
					});
				});
			});
		},
		yes: function(index, layero){
			var postData = {'infoItems':JSON.stringify(table.cache.dhtable_c),'gprovide':gprovide};//转化为json字符串格式
		    $.operate.post('/crm/providermainbrand/additems', postData,function(res){
		    	if(res.code==0){
		    		var mainBrandStr='';
		    		$.each(table.cache.dhtable_c,function(i,v){
		    			mainBrandStr+=v.mainBrand+'，';
					});
		    		$('#mainBrand').val(mainBrandStr.substring(0,mainBrandStr.length-1));
		    		setTimeout(function(){
		    			layer.closeAll();
		    		},1500);
		    	}
		    });
		}
	});
	else layer.msg("请先保存后再选择主营品牌！",{icon:7});
}
//保存调用的方法
function submitHandler(saveNew=false) {
	var errorFlag = false;
  if(table.cache.dhtable.length!=0){
  	$.each(table.cache.dhtable,function(i,v){
	       	if(!v["vName"] || !v["vTel"] || !v["vAddress"]){
	       		layer.msg('第'+(i+1)+'行联系人的姓名、电话、地址为必填，请检查！', {icon: 2});
	       		errorFlag = true;
	       		return false;
	       	}
  	});
  	if(errorFlag)return false;//退出保存
		if($("#gprovide").val()){//修改供应商
			$.each(table.cache.dhtable,function(i,v){
				if(v["newData"]==1)v["guid"]=$("#guid").val();//如果是新增联系人，则带上供应商资料的guid，新增查询gprovide
			})
			$.operate.post(prefix1 + "/editpost",{'providerInfoItems':JSON.stringify([$.common.formToJSON('form-provider-add')])},function(res){//修改供应商
				if(res.code==0)$.operate.post(prefix2 + "/editpost", {'providerPersionInfoItems':JSON.stringify(table.cache.dhtable, null, 2)});//覆盖联系人
				else $.operate.ajaxSuccess(res);
			});
		}else{//新增供应商
			$.each(table.cache.dhtable,function(i,v){
				v["guid"]=$("#guid").val();//通过供应商guid查询gprovide
			})
			$.operate.post(prefix1 + "/addpost", {'providerInfoItems':JSON.stringify([$.common.formToJSON('form-provider-add')])},function(res){//新增供应商
				if(res.code==0){
					$.operate.post(prefix2 + "/addpost", {'providerPersionInfoItems':JSON.stringify(table.cache.dhtable, null, 2)},function(res2){//新增联系人
						if(res2.code==0){
							if(saveNew)setTimeout(function(){window.location.reload();}, 2000);
							else{
								var tabTitleObj = $('.layui-tab-title', parent.document).find('.layui-this').find('span');//当前tab对象
								var tabName = tabTitleObj.html();
								tabName = tabName.replace(' - 新增','('+res.data.gprovide+') - 修改');
								tabTitleObj.html(tabName);
								window.location.href = prefix1+'/edit?gprovide='+res.data.gprovide;
							}
						}
					});
				}else $.operate.ajaxSuccess(res);
			});
		}
  }else layer.msg('请添加至少一名联系人！', {icon: 2});
}
function uploadFile(){
	getUploadCommon("vProviderFiles", "Head", gprovide);
}
</script>
</body>
</html>